<template>
  <div class="code-layout">
    <div class="menu-left">
      <el-menu
        :unique-opened="true"
        :style="{
          position,
        }"
        class="el-menu-vertical">
        <div v-for="(e, i) in menu" :key="i">
          <el-submenu :index="String(i)" class="submenu-item" v-if="e.children && e.children.length">
            <template slot="title">
              <span class="h1-blod" slot="title" :title="e.title">{{ e.title }}</span>
            </template>
            <el-menu-item
              v-for="(ele, index) in e.children"
              :key="index"
              @click="anchor(ele)"
              :index="`${i}-${index}`">
              <span class="h2-blod" :title="ele">{{ ele }}</span>
            </el-menu-item>
          </el-submenu>
          <el-menu-item
            :index="String(i)"
            class="submenu-item"
            @click="anchor(e.title)"
            v-else>
            <span class="h1-blod" slot="title" :title="e.title">{{ e.title }}</span>
          </el-menu-item>
        </div>
      </el-menu>
    </div>
    <div class="markdown-box">
      <div v-html="readmeHtml" class="markdown-body" v-if="readmeHtml"></div>
    </div>
  </div>
</template>
<script>
//  实训概览

import marked from "marked";

export default {
  data() {
    return {
      readmeHtml: "",
      content: '',
      istop: false,
      t: 0,
      position: 'absolute',
      menu: []
    };
  },
  props: ['value'],
  components: {  },
  methods: {
    getChild(tag, html) {
      let temp = false
      let child = tag.getElementsByTagName('*')
      for (let i = 0; i < child.length; i++) {
        if (child[i].innerHTML.trim() == html.trim()) {
          console.log(child[i])
          temp = true
        }
      }
      return tag.innerHTML == html || temp
    },
    getByHtml(html) {
      let temp = null
      let h1 = document.querySelector('.markdown-box').getElementsByTagName('h1')
      let h2 = document.querySelector('.markdown-box').getElementsByTagName('h2')
      let tag = [...h1, ...h2]
      for (let i = 0; i < tag.length; i ++) {
        if (this.getChild(tag[i], html)) {
          temp = tag[i]
          break
        }
      }
      return temp
    },
    anchor(e) {
      let ele = this.getByHtml(e)
      console.log(ele)
      if (ele) {
        window.scroll(0, ele.offsetTop)
      }
    }
  },

  watch: {
    
  },
  created() {
  },
  mounted() {
    this.readmeHtml = marked(this.value)

    
    this.$nextTick(() => {
      let tag = document.querySelector('.markdown-body').querySelectorAll('h1,h2')
      let h1 = document.querySelector('.markdown-body').querySelectorAll('h1')
      let tagArray = Array.from(tag)
      let index = []
      console.log(tagArray)
      h1.forEach(e => {
        index.push(tagArray.indexOf(e))
      })
      let temp = []
      for (let i = 0; i < index.length; i ++) {
        if (index[i + 1]) {
          console.log(index[i], index[i + 1] - index[i])
          temp.push(tagArray.slice(index[i], index[i + 1]))
        } else {
          console.log(index[i], tagArray.length - index[i])
          temp.push(tagArray.splice(index[i], tagArray.length))
        }
      }
      console.log(temp)
      let temp2 = []
      temp.forEach((e, i) => {
        let t = {}
        let children = e.filter(e => e.tagName == 'H2')
        if (h1[i]) {
          t.title = h1[i].innerText
        }
        let c = [...children]
        t.children = c.map(e => e.innerText)
        temp2.push(t)
      })
      this.menu = temp2
      let top = document.querySelector('.menu-left').offsetTop 
      this.t = top
      
      window.addEventListener('scroll', () => {
        if (document.documentElement.scrollTop > top) {
          this.istop = true
          // this.t = 0
          this.position = 'fixed'
        } else {
          this.istop = false
          // this.t = top
          this.position = 'absolute'
        }
      })
    })

    let isMathjaxConfig = false; // 防止重复调用Config，造成性能损耗

    const initMathjaxConfig = () => {
      if (!window.MathJax) {
        return;
      }
      window.MathJax.Hub.Config({
        showProcessingMessages: false, //关闭js加载过程信息
        messageStyle: "none", //不显示信息
        jax: ["input/TeX", "output/HTML-CSS"],
        tex2jax: {
          inlineMath: [
            ["$", "$"],
            ["\\(", "\\)"],
          ], //行内公式选择符
          displayMath: [
            ["$$", "$$"],
            ["\\[", "\\]"],
          ], //段内公式选择符
          skipTags: [
            "script",
            "noscript",
            "style",
            "textarea",
            "pre",
            "code",
            "a",
          ], //避开某些标签
        },
        "HTML-CSS": {
          availableFonts: ["STIX", "TeX"], //可选字体
          showMathMenu: false, //关闭右击菜单显示
        },
      });
      isMathjaxConfig = true; //
    };
    if (isMathjaxConfig === false) {
      // 如果：没有配置MathJax
      initMathjaxConfig();
    }

    // 如果，不传入第三个参数，则渲染整个document
    // 因为使用的Vuejs，所以指明#app，以提高速度
    setTimeout(() => {
      window.MathJax && window.MathJax.Hub.Queue([
        "Typeset",
        window.MathJax.Hub,
        document.getElementById("app"),
      ]);
    }, 500);
  },
  destroyed() {},
};
</script>

<style lang="less" scoped>
.code-layout {
  padding: 0 0 40px;
  display: flex;
  // position: relative;
  .menu-left{
    position: relative;
    width: 280px;
    .el-menu-vertical{
      width: 260px;
      height: 100%;
      top: 0;
      left: 10px;
    }
    .is-top{
      top: 0;
    }
  }
  .markdown-box{
    flex: 1;
    .markdown-body{
      max-width: 1000px;
      margin: 0 auto;
      padding-top: 40px;
    }
  }
}
.h1-blod{
  font-weight: bold;
  font-size: 16px;
  color: #2f3032;
  width: 200px;
  white-space:nowrap;
  text-overflow:ellipsis;
  display: block;
  overflow: hidden;
}
.h2-blod{
  color: #2f3032;
  width: 200px;
  white-space:nowrap;
  text-overflow:ellipsis;
  display: block;
  overflow: hidden;
}
</style>
